<?php

declare(strict_types=1);

namespace app\common\service\im;

use app\common\traits\ServiceTrait;
use app\common\dao\im\ChatlogDao;
use app\common\service\pmm\MessageService;

/**
 * 聊天记录 - 业务
 * @author:kaige
 * @update:2022-06-12
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class ChatlogService
{
  protected $dao = null;

  public function __construct()
  {
    $this->dao = new ChatlogDao();
  }
  use ServiceTrait;

  /**
   * 重写 列表过滤条件
   * @param $post
   * @return array
   */
  public function _list_where($post)
  {
    $where = [];
    if (isset($post['send_id']) && $post['send_id'] != "") {
      $where[] = ['send_id', '=', $post['send_id']];
    }
    if (isset($post['rece_id']) && $post['rece_id'] != "") {
      $where[] = ['rece_id', '=', $post['rece_id']];
    }
    if (isset($post['chat_type']) && $post['chat_type'] != "") {
      $where[] = ['chat_type', '=', $post['chat_type']];
    }
    if (isset($post['search_chat_type']) && $post['search_chat_type'] != "") {
      $where[] = ['chat_type', '=', $post['search_chat_type']];
    }
    if (isset($post['group_id']) && $post['group_id'] != "") {
      $where[] = ['group_id', '=', $post['group_id']];
    }
    if (isset($post['status']) && $post['status'] != "") {
      $where[] = ['status', '=', $post['status']];
    }
    if (isset($post['keywords']) && !empty($post['keywords'])) {
      $where[] = ['content', 'like', '%' . $post['keywords'] . '%'];
    }

    $result['where'] = $where;
    $result['field'] = [];
    $result['order'] = ['id desc'];
    return $result;
  }

  // 取出我发送的与我接收的
  public function getUserChatList($uid = 0)
  {
    $list = $this->dao->getUserChatList($uid);
    if (isset($list['list']) && $list['list']) {
      foreach ($list['list'] as $k => $v) {
        $id = $v['send_id'] == $uid ? $v['rece_id'] : ($v['rece_id'] == $uid ? $v['send_id'] : 0);
        //取与对象的聊天的 消息未读条数
        if ($id) {
          $list['list'][$k]['badge'] = $this->dao->getBadgeNumber($id, $uid);
        }
      }
    }
    return $list;
  }

  // 取出我与聊天对象的 我发送的与我接收的
  public function getUserChatObjList($data = [])
  {
    //已读
    if (isset($data['read']) && $data['read'] == 1) {
      $this->dao->readUpdate($data);
    }
    $list =  $this->dao->getUserChatObjList($data);
    if (count($list) > 0) {
      foreach ($list as $k => $v) {
        if (isset($v['avatar'])) {
          $list[$k]['avatar'] = _img($v['avatar']);
        }
        if (isset($v['files_id'])) {
          $list[$k]['files_url'] = _img($v['files_id']);
        }
      }
    }
    return $list;
  }

  // 取出群聊记录
  public function getUserGroupChatList($data)
  {
    $list =  $this->dao->getUserGroupChatList($data);
    if (count($list) > 0) {
      foreach ($list as $k => $v) {
        if (isset($v['avatar'])) {
          $list[$k]['avatar'] = _img($v['avatar']);
        }
        if (isset($v['files_id'])) {
          $list[$k]['files_url'] = _img($v['files_id']);
        }
      }
    }
    return $list;
  }
}
